/*
 * Copyright (c) 2024 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import { driver } from 'gremlin';
import path from 'path';
import * as fs from 'fs';

class GremlinClient {
    private readonly client: driver.Client;

    public constructor(configPath?: string) {
        if (configPath === undefined) {
            configPath = path.resolve(__dirname, 'config.json');
        }
        const configfile = JSON.parse(fs.readFileSync(configPath, 'utf-8'));

        const remote = configfile.gremlinConfig;
        this.client = new driver.Client(remote, {
            traversalSource: 'g',
            mimeType: 'application/json',
        });
    }

    public async submit(cypher: string, bindings: object): Promise<void> {
        await this.client.submit(cypher, bindings);

    };
    public async close(): Promise<void> {
        await this.client.close();
      }
    public getClient() {
        return this.client;
    }
}

export class Connection {
    public static readonly client = new GremlinClient();

    public static async clearGraph() {
        await this.client.getClient().submit('g.V().drop().iterate()');
    }

    public static async getClient(){
        await Connection.clearGraph();
        return Connection.client.getClient();
    }
}
